/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.jm.financeiro.base.util;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author joao
 */
public final class JPAUtil implements Serializable {

    private static EntityManagerFactory FABRICA;
    private final static Logger logger = Logger.getLogger(JPAUtil.class.getName());
    private static final long serialVersionUID = 1424864854905019728L;

    /** Contrutor privado. **/
    private JPAUtil() {
    }

    public synchronized static void carregarFabrica() {
        if (FABRICA == null) {
            try {
                FABRICA = Persistence.createEntityManagerFactory("financeiroPU");
                //System.out.println("Fabrica carregada com sucesso.");
                Logger.getLogger(JPAUtil.class.getName()).log(Level.SEVERE, null, "");
            } catch (Exception e) {
                //e.printStackTrace();
                Logger.getLogger(JPAUtil.class.getName()).log(Level.SEVERE, null, "");
                throw new RuntimeException("Erro na criação da  fabrica - "
                        + e.getMessage());
            }
        }
    }

    public static EntityManager getSession() {
        if (FABRICA == null) {
            throw new RuntimeException(
                    "EntityManagerFactory intranet não foi carregada.");
        } else {
            synchronized (FABRICA) {
                return FABRICA.createEntityManager();
            }
        }
    }

    public static void destruirFabrica() {
        if (FABRICA != null) {
            synchronized (FABRICA) {
                FABRICA.close();
                //System.out.println("Fabrica destruida com sucesso.");
                Logger.getLogger(JPAUtil.class.getName()).log(Level.SEVERE, null, "");
            }
        }
    }
}
